package com.shanks.home.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

import com.shanks.home.util.LogUtil;

/**
 * @author Shanks
 * @time 2013.12.10
 * 封装一套
 */
public class SocketService {

	private static final String TAG = SocketService.class.getSimpleName();
	private Socket socket;
	private OutputStream outputStream;
	private InputStream inputStream;

	private Thread receiverThead;
	private SocketResponser socketResponser;

	public SocketService(SocketResponser sr) {
		socketResponser = sr;
	}

	public boolean Connect(String ip, int port) throws IOException {
		boolean result = false;

		close();

		LogUtil.i("", "ip:" + ip);
		LogUtil.i("", "port:" + port);

		socket = new Socket();
		InetSocketAddress inetSocketAddress = new InetSocketAddress(ip, port);
		socket.connect(inetSocketAddress);
		result = socket.isConnected();
		if (result) {
			outputStream = socket.getOutputStream();
			inputStream = socket.getInputStream();
			startThread();
		}

		return result;
	}

	public void close() throws IOException {
		if (receiverThead != null) {
			stopThread();
		}
		if (socket != null) {
			socket.close();
			socket = null;
		}
	}

	public int send(byte[] buffer, int count) throws IOException {
		int result = -1;
		if (socket == null) {
			return result;
		}

		if (socket.isClosed() || socket.isOutputShutdown() || !socket.isConnected()) {
			return result;
		}

		outputStream.write(buffer, 0, count);
		outputStream.flush();
		result = count;

		return count;
	}

	private void startThread() {
		if(null != receiverThead){
			stopThread();
		}

		receiverThead = new Thread(new ReceiverThread(), "receive_thread");
		receiverThead.start();
	}

	private void stopThread() {
		receiverThead.interrupt();
		receiverThead = null;
	}

	private  class ReceiverThread implements Runnable{

		@Override
		public void run() {
			while(!Thread.currentThread().isInterrupted()){
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					break;
				}

				if(null == socket || !socket.isConnected()){
					break;
				}

				try {
					inputStream = socket.getInputStream();
					if(!socket.isInputShutdown() && inputStream != null) {
						
//						LogUtil.i(TAG, "get socket");
						socketResponser.onReceive(inputStream);
						LogUtil.i(TAG, "get socket  111");
					}
				} catch (Exception e) {
//					LogUtil.i(TAG, "get socket  222");
					if(!Thread.currentThread().isInterrupted()) {
						try {
							//							onReceiver.onReceive(null);
						} catch (Exception e1) {
						}
					} else {
						break;
					}
				}
			}
		}

	}


	public boolean isConnected() {
		if (socket == null) {
			return false;
		}
		return socket.isConnected();
	}
}
